package com.ingenio.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.ingenio.business.Pedido;
import com.ingenio.dao.PedidoAdapter;

/**
 * Servlet implementation class CancelarPedidoServlet
 */
@WebServlet("/CancelarPedido")
public class CancelarPedidoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CancelarPedidoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect("index.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(request.getParameter("id") != "" && ObtenerProductoServlet.isNumeric(request.getParameter("id"))){
			PedidoAdapter pa = new PedidoAdapter();
			Integer id = Integer.parseInt(request.getParameter("id"));
			Pedido p = null;
			JSONObject json = new JSONObject();
			try {
				p = pa.devolverPedido(id);
				if(p.getEstadoPedido().getIdEstadoPedido() == 1 || p.getEstadoPedido().getIdEstadoPedido() == 3){
					pa.cancelarPedido(p);
					json.put("error", false);
					json.put("id", p.getIdPedido());
				}else{
					json.put("error", "error");
					json.put("msj", "El pedido ya se encuentra cancelado");
				}
				
			} catch (Exception e) {
				try {
					json.put("error", "error");
					json.put("msj", "Error al tratar de cancelar pedido");
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			response.sendRedirect("index.jsp");
					
		}
	}

}
